package com.example.taobaounion.view.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.taobaounion.R;
import com.example.taobaounion.model.domain.SelectedPageCategory;

import java.util.ArrayList;
import java.util.List;

public class SelectedPageLeftAdapter extends RecyclerView.Adapter<SelectedPageLeftAdapter.InnerHolder> {

    private List<SelectedPageCategory.DataBean> mData = new ArrayList<>();
    private int mCurrentSelectedPostion = 0;
    private onLeftItemClickListener mItemClickListener;

    @NonNull
    @Override
    public InnerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_selected_page_left, parent, false);

        return new InnerHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull InnerHolder holder, int position) {
        TextView itemTv = holder.itemView.findViewById(R.id.left_category_tv);

        if (mCurrentSelectedPostion == position) {
            itemTv.setBackgroundColor(itemTv.getResources().getColor(R.color.color_EFEEEE));
        } else {
            itemTv.setBackgroundColor(itemTv.getResources().getColor(R.color.white));
        }

        SelectedPageCategory.DataBean dataBean = mData.get(position);


        itemTv.setText(dataBean.getFavorites_title());

        holder.itemView.setOnClickListener(v -> {
            if (mCurrentSelectedPostion != position) {
                mCurrentSelectedPostion = position;

                if (mItemClickListener != null) {
                    mItemClickListener.onLeftItemClick(mData.get(mCurrentSelectedPostion));
                }
                notifyDataSetChanged();
            }
        });
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public void setData(SelectedPageCategory categorys) {
        List<SelectedPageCategory.DataBean> data = categorys.getData();

        if (data != null) {
            mData.clear();
            mData.addAll(data);
            notifyDataSetChanged();
        }

        if (mData.size() > 0) {
            mItemClickListener.onLeftItemClick(mData.get(mCurrentSelectedPostion));
        }
    }

    static class InnerHolder extends RecyclerView.ViewHolder {
        InnerHolder(@NonNull View itemView) {
            super(itemView);
        }
    }

    public void setonLeftItemClickListener(onLeftItemClickListener listener) {
        this.mItemClickListener = listener;
    }

    public interface onLeftItemClickListener {
        void onLeftItemClick(SelectedPageCategory.DataBean dataBean);
    }
}
